<template lang="html">
  <div v-loading="loading" class="main-panel">
    <el-button type="primary" @click="productDialog('post')">添加</el-button>
    <el-dialog v-loading="loading" title="编辑" :visible.sync="productDiaIsShow" class="diaForm" :append-to-body="false">
      <el-form
        ref="productRef"
        :model="productForm"
        :rules="productRules"
        label-width="140px"
      >
        <el-form-item label="商品名称" prop="product_name">
          <el-col :span="15">
            <el-input
              v-model="productForm.product_name"
              type="text"
              placeholder="请填写商品名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="相关图片">
          <el-col :span="6">
            Logo
            <el-upload
              class="avatar-uploader"
              :action="uploadMediaAction"
              :show-file-list="false"
              :headers="{'authorization': token}"
              :on-success="handleLogoSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="logo_url" :src="logo_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </el-col>
          <el-col :span="6">
            分享图
            <el-upload
              class="avatar-uploader"
              :action="uploadMediaAction"
              :show-file-list="false"
              :headers="{'authorization': token}"
              :on-success="handleShareSuccess">
              <img v-if="share_url" :src="share_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
          <el-col :span="6">
            微信分享图
            <el-upload
              class="avatar-uploader"
              :action="uploadMediaAction"
              :show-file-list="false"
              :headers="{'authorization': token}"
              :on-success="handleWechatShareSuccess">
              <img v-if="wechat_share_url" :src="wechat_share_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
          <el-col :span="6">
            小程序分享图
            <el-upload
              class="avatar-uploader"
              :action="uploadMediaAction"
              :show-file-list="false"
              :headers="{'authorization': token}"
              :on-success="handleMiniShareSuccess">
              <img v-if="mini_share_url" :src="mini_share_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
          <el-col :span="24">
            <el-col :span="24">
              商品图
            </el-col>
            <el-col v-for="(item, itemIndex) in image_urls" :span="6">
              <el-upload
                class="avatar-uploader"
                :action="uploadMediaAction"
                :show-file-list="false"
                :headers="{'authorization': token}"
                :on-success="(res, file) => handleImageSuccess(res, file, itemIndex)">
                <img v-if="item.url" :src="item.url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-col>
            <el-col :span="6" @click.native="addImageUrls()" v-if="imageUrlsAddDiv">
              <div style="font-weight: 200;font-size: 50px;height: 178px;line-height: 178px;text-align: center"> +</div>
            </el-col>
          </el-col>
        </el-form-item>
        <el-form-item label="商品类目" prop="product_category_id">
          <el-col :span="15">
            <el-select
              v-model="productForm.product_category_id"
              filterable
              remote
              reserve-keyword
              clearable
              placeholder="请选择商品类目"
              :remote-method="getProductCategoryRemote"
              :loading="loading"
            >
              <el-option
                v-for="v in categoryOptions"
                :key="v.id"
                :label="v.name"
                :value="v.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="商品规格">
          <el-col v-for="(item, index) in productForm.product_attr_info" :span="24">
            <el-col :span="8">
              <!--              <el-input-->
              <!--                v-model="productForm.product_attr_info[index].attr"-->
              <!--                placeholder="请填写规格名(容量、颜色等)"></el-input>-->
              <el-select
                v-model="productForm.product_attr_info[index].attr"
                filterable
                allow-create
                default-first-option
                placeholder="请填写规格名(容量、颜色等)"
                @change="(v) => changeAttrGroupName(v, index)"
              >
                <el-option
                  v-for="attr in ['容量','颜色','套装']"
                  :key="attr"
                  :label="attr"
                  :value="attr"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select
                v-model="productForm.product_attr_info[index].sku_names"
                multiple
                :multiple-limit="5"
                filterable
                allow-create
                default-first-option
                placeholder="请填写规格值"
              />
            </el-col>
            <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteAttrGroupProject(index)">删除规格项目
            </el-button>
          </el-col>
          <el-col :span="24">
            <el-button @click="addAttrGroupProject()">添加规格项目</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="规格明细">
          <el-row>
            <el-col :span="4">规格名</el-col>
            <el-col :span="4">价格</el-col>
            <el-col :span="4">库存</el-col>
            <el-col :span="4">虚拟销量</el-col>
            <el-col :span="4">成本价</el-col>
            <el-col :span="4">规格图</el-col>
          </el-row>
          <el-row>
            <el-col v-for="(sku, index) in skuArr" :span="24">
              <el-col :span="4">{{ sku.sku_name }}</el-col>
              <el-col :span="4">
                <el-input v-model="sku.price" type="number" placeholder="请输入价格" @input="forceUpdate()"/>
              </el-col>
              <el-col :span="4">
                <el-input v-model="sku.stock" type="number" placeholder="请输入库存" @input="forceUpdate()"/>
              </el-col>
              <el-col :span="4">
                <el-input v-model="sku.virtual_sales" type="number" placeholder="请输入虚拟销量" @input="forceUpdate()"/>
              </el-col>
              <el-col :span="4">
                <el-input v-model="sku.cost_price" type="number" placeholder="请输入成本价" @input="forceUpdate()"/>
              </el-col>
              <el-col :span="4">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadMediaAction"
                  :show-file-list="false"
                  :headers="{'authorization': token}"
                  :on-success="(res, file) => handleSkuLogoSuccess(res, file, index)">
                  <img v-if="sku.logo_url" :src="sku.logo_url" class="avatar" style="width: 150px;height: 150px">
                  <i v-else class="el-icon-plus avatar-uploader-icon" style=""></i>
                </el-upload>
                <!--                <el-input v-model="" type="number" placeholder="请输入成本价" @input="forceUpdate()"/>-->
              </el-col>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="状态" prop="product_status">
          <el-col :span="24">
            <el-switch
              v-model="productForm.product_status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="上架"
              inactive-text="下架">
            </el-switch>
          </el-col>
        </el-form-item>
        <el-form-item label="商品标签(功效)" prop="product_tags">
          <el-col :span="24">
            <el-select
              v-model="productForm.product_tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请填写商品标签(功效)">
              <el-option
                v-for="item in {}"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="赠送的积分比例" prop="product_gift_points_proportion">
          <el-col :span="4">
            <el-input
              v-model="productForm.product_gift_points_proportion"
              type="number"
              placeholder="请填写赠送的积分比例，默认是1"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="商品描述" prop="product_desc">
          <el-col :span="24">
            <editor
              id="productDescEditor"
              v-model="productForm.product_desc"
              :init="editorInit"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editProduct()"
          >确认
          </el-button>
          <el-button @click="productDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      :data="productTableData"
      border
      style="width: 100%"
    >
      <el-table-column
        label="商品信息"
        width="250"
      >
        <template slot-scope="scope">
          <el-col :span="24">商品ID：{{ scope.row.id }}</el-col>
          <el-col :span="24">商品名：{{ scope.row.name }}</el-col>
          <el-col :span="24">商品分类名：{{ scope.row.categoryInfo.name }}</el-col>
          <el-col :span="24">创建时间：{{ scope.row.create_time }}</el-col>
          <el-col :span="24">更新时间：{{ scope.row.update_time }}</el-col>
        </template>
      </el-table-column>
      <el-table-column
        label="Logo图"
        align="center"
      >
        <template slot-scope="scope">
          <img :src="scope.row.logo_url" alt="" width="100px;">
        </template>
      </el-table-column>
      <el-table-column
        label="分享图"
        align="center"
      >
        <template slot-scope="scope">
          <img :src="scope.row.share_url" alt="" width="100px;">
        </template>
      </el-table-column>
      <el-table-column
        label="微信分享图"
        align="center"
      >
        <template slot-scope="scope">
          <img :src="scope.row.wechat_share_url" alt="" width="100px;">
        </template>
      </el-table-column>
      <el-table-column
        label="小程序分享图"
        align="center"
      >
        <template slot-scope="scope">
          <img :src="scope.row.mini_share_url" alt="" width="100px;">
        </template>
      </el-table-column>
      <el-table-column
        label="商品图"
      >
        <template slot-scope="scope">
          <el-col :span="24" v-for="item in scope.row.image_urls">
            <img :src="item" alt="" width="100px;">
          </el-col>
        </template>
      </el-table-column>
      <el-table-column
        prop="extend_status_text"
        label="商品状态"
      />
      <el-table-column
        label="规格"
        width="600"
      >
        <template slot-scope="scope">
          <el-col v-for="item in scope.row.skuInfo" :span="24">
            规格名：{{ item.sku_name }}
            单价：{{ item.price }}
            成本价：{{ item.cost_price }}
            库存：{{ item.stock }}
            虚拟销量：{{ item.virtual_sales }}
          </el-col>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="productDialog('put',scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteProduct(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px">
      <el-pagination
        :current-page="productTableDataPaginateCurrentPage"
        :page-sizes="productTableDataPaginateTotalPageSizes"
        :page-size="productTableDataPaginateTotalPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="productTableDataPaginateTotal"
        @size-change="productTableDataHandleSizeChange"
        @current-change="productTableDataHandleCurrentChange"
      >
        <!-- <span>当前{{ productTableDataPaginateCurrentPage }}页，</span>
                        <span>共{{ productTableDataPaginateLastPage }}页</span> -->
      </el-pagination>
    </div>
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
import { descartes, ksort } from '@/utils'
import {
  getToken
} from '@/utils/auth'

export default {
  components: {
    'editor': Editor
  },
  data() {
    return {
      loading: false,
      categorySearchForm: {},
      categoryTableData: [],
      categoryOptions: [],
      attrGroupSearchForm: {},
      attrGroupTableData: [],
      attrGroupOptions: [],
      productSearchForm: {},
      productTableData: [],
      productTableDataPaginateCurrentPage: 1,
      productTableDataPaginateTotal: 1,
      productTableDataPaginateLastPage: 1,
      productTableDataPaginateTotalPageSize: 10,
      productTableDataPaginateTotalPageSizes: [10, 20, 50, 100],
      productTab: [],
      productEditType: 'post',
      productDiaIsShow: false,
      productForm: {
        product_status: true,
        product_tags: [],
        product_gift_points_proportion: 1,
        product_attr_info: [
          { attr: null, sku_names: [] }
        ],
        product_desc: ''
      },
      // sku: [
      //   // {
      //   //     sku_name: null,
      //   //     price: null,
      //   //     stock: null,
      //   //     virtual_sales: null,
      //   //     cost_price: null
      //   //     logo_url: null
      //   // }
      // ],
      productRules: {
        product_name: [{
          required: true,
          trigger: 'blur'
        }],
        product_category_id: [{
          required: true,
          trigger: 'blur'
        }],
        product_tags: [{
          required: true,
          trigger: 'blur'
        }],
        product_gift_points_proportion: [{
          required: true,
          trigger: 'blur'
        }]
      },
      skuServerData: [],
      logo_url: '',
      share_url: '',
      wechat_share_url: '',
      mini_share_url: '',
      image_urls: [{ url: '' }],
      imageVisible: false,
      imageDisabled: false,
      editorInit: {
        selector: '#productDescEditor',
        base_url: 'static/js/tinymce5.4.1/',
        // skin_url: 'static/js/tinymce5.4.1/langs/zh_CN.js',
        height: 500,
        language: 'zh_CN',
        content_style: 'p > img{ max-width: 100%}',
        images_upload_handler: function uploadHandler(blobInfo, success, failure, progress) {
          var blobInfoDetail = blobInfo.blob()
          var valid_extensions = ['png', 'jpg', 'gif']
          var ext, extensions

          extensions = {
            'image/jpeg': 'jpg',
            'image/jpg': 'jpg',
            'image/gif': 'gif',
            'image/png': 'png'
          }

          ext = extensions[blobInfoDetail.type.toLowerCase()] || 'dat'
          // add your extension test here.
          if (valid_extensions.indexOf(ext) === -1) {
            failure('Invalid extension')
            return
          }
          if (blobInfoDetail.size && blobInfoDetail.size > 10000000) {
            failure('图片大小不能超过10Mb')
            return
          }

          var xhr, formData
          xhr = new XMLHttpRequest()
          xhr.withCredentials = false
          xhr.open('POST', process.env.VUE_APP_BASE_API + '/media/upload/file')
          xhr.setRequestHeader('authorization', getToken())
          xhr.upload.onprogress = function(e) {
            progress(e.loaded / e.total * 100)
          }
          xhr.onload = function() {
            var code = xhr.status.toString()
            var startChar = code.charAt(0)
            var json = JSON.parse(xhr.responseText)
            if (startChar === '2') {
              success(json.data.url)
            } else {
              failure(json.msg)
            }
          }
          xhr.onerror = function() {
            failure('上传错误. 代码: ' + xhr.status)
          }
          formData = new FormData()
          formData.append('file', blobInfo.blob(), blobInfo.filename())
          xhr.send(formData)
        },
        plugins: [
          'advlist autolink lists link image charmap print preview anchor',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount'
        ],
        toolbar: 'undo redo|formatselect|bold italic backcolor|alignleft aligncenter alignright alignjustify |bullist numlist outdent indent|removeformat |image|help'
      }
    }
  },
  computed: {
    // 计算属性的 getter
    skuArr: function() {
      // let attr_names = []
      var sku_names = [], product_attr_info = [], res = []
      for (let i = 0; i < this.productForm.product_attr_info.length; i++) {
        // 整理数据，排序
        // eslint-disable-next-line vue/no-side-effects-in-computed-properties
        sku_names.push(this.productForm.product_attr_info[i].sku_names.sort())
      }

      // 制作成sku_name
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties,prefer-const
      product_attr_info = descartes(sku_names)
      console.log(product_attr_info, 'product_attr_info')
      for (let i = 0; i < product_attr_info.length; i++) {
        res.push(
          {
            sku_name: product_attr_info[i].join('*'),
            price: 0,
            stock: 0,
            virtual_sales: 0,
            cost_price: 0,
            logo_url: null
          }
        )
      }

      //回显
      for (let i = 0; i < this.skuServerData.length; i++) {
        for (let j = 0; j < res.length; j++) {
          if (this.skuServerData[i].sku_name === res[j].sku_name) {
            res[j].cost_price = this.skuServerData[i].cost_price
            res[j].price = this.skuServerData[i].price
            res[j].sales = this.skuServerData[i].sales
            res[j].virtual_sales = this.skuServerData[i].virtual_sales
            res[j].stock = this.skuServerData[i].stock
            res[j].logo_url = this.skuServerData[i].logo_url
          }
        }
      }
      this.forceUpdate()
      console.log(res)
      return res
    },
    attrGroupOptionsTrue: function() {
      let res = []
      // console.log(this.attrGroupTableData)
      for (let i = 0; i < this.attrGroupTableData.length; i++) {
        if (this.productForm.product_category_id === this.attrGroupTableData[i].category_id) {
          res.push(this.attrGroupTableData[i])
        }
      }
      return res
    },
    uploadMediaAction: function() {
      return process.env.VUE_APP_BASE_API + '/media/upload/file'
    },
    token: function() {
      return getToken()
    },
    imageUrlsAddDiv: function() {
      let res = true
      for (let i = 0; i < this.image_urls.length; i++) {
        if (this.image_urls[i].url === '') {
          res = false
          break
        }
      }
      return res
    }
  },
  created() {
    this.getCategoryList(1, 10000)
    // this.getAttrGroupList(1, 10000)
    this.getProductList()
  },
  methods: {
    handleLogoSuccess(res, file) {
      console.log(res)
      // this.logo_url = URL.createObjectURL(file.raw)
      this.logo_url = res.data.url
    },
    handleShareSuccess(res, file) {
      console.log(res)
      this.share_url = res.data.url
    },
    handleWechatShareSuccess(res, file) {
      console.log(res)
      this.wechat_share_url = res.data.url
    },
    handleMiniShareSuccess(res, file) {
      console.log(res)
      this.mini_share_url = res.data.url
    },
    handleSkuLogoSuccess(res, file, index) {
      console.log(res, index)
      this.skuArr[index].logo_url = res.data.url
      console.log(this.skuArr)
      this.$forceUpdate()
    },
    handleImageSuccess(res, file, index) {
      console.log(res, file, index)
      this.image_urls[index].url = res.data.url
      console.log(this.image_urls)
    },
    addImageUrls(res, file, index) {
      this.image_urls.push({ url: '' })
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt2M = file.size / 1024 / 1024 < 2
      //
      // // if (!isJPG) {
      // //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    changeAttrGroupName(v, index) {
      let count = 0
      for (let i = 0; i < this.productForm.product_attr_info.length; i++) {
        if (this.productForm.product_attr_info[i].attr === v) {
          count++
        }
      }
      if (count > 1) {
        this.productForm.product_attr_info.splice(index, 1)
        this.$message.error('重复添加商品规格')
      }
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    productFormInit() {
      this.product_attr_name = []
      // this.$nextTick(() => {
      //   this.$set(this.productForm, 'product_name', row.name)
      // })
    },
    addAttrGroupProject() {
      if (this.productForm.product_attr_info.length > 5) {
        this.$message.error('最大不能超过10个')
        return false
      }
      for (let i = 0; i < this.productForm.product_attr_info.length; i++) {
        if (this.productForm.product_attr_info[i].sku_names.length === 0) {
          this.$message.error('请填写数据后再进行添加')
          return false
        }
      }
      this.productForm.product_attr_info.push({
        attr: null,
        sku_names: []
      })
    },
    huixianSkuInfo() {
      // 回显
      for (let i = 0; i < this.skuServerData.length; i++) {
        for (let j = 0; j < this.skuArr.length; j++) {
          if (this.skuServerData[i].sku_name === this.skuArr[j].sku_name) {
            this.skuArr[j].cost_price = this.skuServerData[i].cost_price
            this.skuArr[j].price = this.skuServerData[i].price
            this.skuArr[j].sales = this.skuServerData[i].sales
            this.skuArr[j].virtual_sales = this.skuServerData[i].virtual_sales
            this.skuArr[j].stock = this.skuServerData[i].stock
            this.skuArr[j].logo_url = this.skuServerData[i].logo_url
          }
        }
      }
    },
    deleteAttrGroupProject(k) {
      this.productForm.product_attr_info.splice(k, 1)
      this.huixianSkuInfo()
    },
    getProductCategoryRemote(query) {
      if (query !== '') {
        this.categoryOptions = this.categoryTableData.filter(item => {
          return item.label.toLowerCase()
            .indexOf(query.toLowerCase()) > -1
        })
      } else {
        this.categoryOptions = this.categoryTableData
      }
    },
    getProductAttrGroupRemote(query) {
      if (query !== '') {
        this.attrGroupOptions = this.attrGroupTableData.filter(item => {
          return item.label.toLowerCase()
            .indexOf(query.toLowerCase()) > -1
        })
      } else {
        this.attrGroupOptions = this.attrGroupTableData
      }
    },
    productTableDataHandleSizeChange(val) {
      // 改变每页显示的条数
      this.productTableDataPaginateTotalPageSize = val
      this.getProductList(1, this.productTableDataPaginateTotalPageSize)
    },
    productTableDataHandleCurrentChange(val) {
      this.productTableDataPaginateCurrentPage = val
      this.getProductList(val, this.productTableDataPaginateTotalPageSize)
    },
    getCategoryList(page = 1, limit = 10) {
      this.loading = true
      this.categorySearchForm.page = page
      this.categorySearchForm.limit = limit
      this.$store.dispatch('product/getCategoryList', this.categorySearchForm).then((res) => {
        this.categoryTableData = res.data.data
        this.categoryOptions = res.data.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // getAttrGroupList(page = 1, limit = 10) {
    //   this.loading = true
    //   this.attrGroupSearchForm.page = page
    //   this.attrGroupSearchForm.limit = limit
    //   this.$store.dispatch('product/getProductAttrGroupList', this.attrGroupSearchForm).then((res) => {
    //     this.attrGroupTableData = res.data.data
    //     this.attrGroupOptions = res.data.data
    //     this.loading = false
    //   }).catch(() => {
    //     this.loading = false
    //   })
    // },
    getProductList(page = 1, limit = 10) {
      this.loading = true
      this.productSearchForm.page = page
      this.productSearchForm.limit = limit
      this.$store.dispatch('product/getProductList', this.productSearchForm).then((res) => {
        this.productTableData = res.data.data
        this.productTableDataPaginateTotal = res.data.total
        this.productTableDataPaginateCurrentPage = res.data.current_page
        this.productTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    deleteProduct(row) {
      // console.log(row)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          this.$store.dispatch('product/deleteProduct', { product_id: row.id }).then((res) => {
            this.getProductList()
            this.loading = false
            this.productDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editProduct() {
      switch (this.productEditType) {
        case 'post':
          console.log('skuArr:', this.skuArr)
          // return
          this.$refs['productRef'].validate((valid) => {
            if (valid) {
              if (this.skuArr.length === 0) {
                this.$message.error('请填写sku信息')
                return false
              }
              this.loading = true
              // console.log(this.skuArr)
              this.productForm.product_sku = this.skuArr
              this.productForm.product_logo_url = this.logo_url
              this.productForm.product_share_url = this.share_url
              this.productForm.product_wechat_share_url = this.wechat_share_url
              this.productForm.product_mini_share_url = this.mini_share_url
              this.productForm.product_image_urls = []
              for (let i = 0; i < this.image_urls.length; i++) {
                if (this.image_urls[i].url) {
                  this.productForm.product_image_urls.push(this.image_urls[i].url)
                }
              }
              console.log(this.productForm)
              this.$store.dispatch('product/postProduct', this.productForm).then((res) => {
                this.loading = false
                this.productDiaIsShow = false
                this.$message.success(res.msg)
                this.getProductList()
                this.productFormInit()
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'put':
          this.$refs['productRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              if (this.skuArr.length === 0) {
                this.$message.error('请填写sku信息')
                return false
              }
              // console.log(this.skuArr)
              this.productForm.product_sku = this.skuArr
              this.productForm.product_logo_url = this.logo_url
              this.productForm.product_share_url = this.share_url
              this.productForm.product_wechat_share_url = this.wechat_share_url
              this.productForm.product_mini_share_url = this.mini_share_url
              this.productForm.product_image_urls = []
              for (let i = 0; i < this.image_urls.length; i++) {
                if (this.image_urls[i].url) {
                  this.productForm.product_image_urls.push(this.image_urls[i].url)
                }
              }
              console.log(this.productForm)
              this.$store.dispatch('product/putProduct', this.productForm).then((res) => {
                this.$message.success(res.msg)
                this.productDiaIsShow = false
                this.loading = false
                this.getProductList()
                this.productFormInit()
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
      }
    },
    productDialog(type, row) {
      this.productForm = {
        product_status: true,
        product_tags: [],
        product_gift_points_proportion: 1,
        product_attr_info: [
          { attr: null, sku_names: [] }
        ],
        product_desc: ''
      }
      this.logo_url = ''
      this.share_url = ''
      this.wechat_share_url = ''
      this.mini_share_url = ''
      this.image_urls = [{ url: '' }]
      this.productDiaIsShow = true
      switch (type) {
        case 'post':
          this.productEditType = 'post'
          break
        case 'put':
          this.productEditType = 'put'
          // 这里一定要使用nextTick的方式赋值，不然会卡住input
          this.skuServerData = row.skuInfo
          this.logo_url = row.logo_url
          this.share_url = row.share_url
          this.wechat_share_url = row.wechat_share_url
          this.mini_share_url = row.mini_share_url
          var image_urls = []
          for (let i = 0; i < row.image_urls.length; i++) {
            image_urls.push({ url: row.image_urls[i] })
          }
          this.image_urls = image_urls
          this.$nextTick(() => {
            this.productForm.product_image_urls = []
            for (let i = 0; i < this.image_urls.length; i++) {
              this.productForm.product_image_urls.push(this.image_urls[i].url)
            }

            this.$set(this.productForm, 'product_id', row.id)
            this.$set(this.productForm, 'product_name', row.name)
            this.$set(this.productForm, 'product_category_id', row.category_id)
            this.$set(this.productForm, 'product_desc', row.desc)
            this.$set(this.productForm, 'product_tags', row.tags)
            // var attr_info = [], attrs = []
            // // console.log(row.skuInfo, 'skuInfo')
            // for (let i = 0; i < row.skuInfo.length; i++) {
            //   attrs.push(row.skuInfo[i].attr)
            // }
            // attrs = Array.from(new Set(attrs))
            // for (let i = 0; i < attrs.length; i++) {
            //   attr_info.push({ attr: attrs[i], sku_names: [] })
            // }
            //
            // for (let i = 0; i < row.skuInfo.length; i++) {
            //   for (let j = 0; j < attr_info.length; j++) {
            //     if (attr_info[j].attr === row.skuInfo[i].attr) {
            //       attr_info[j].sku_names.push(row.skuInfo[i].sku_name)
            //     }
            //   }
            // }
            this.$set(this.productForm, 'product_attr_info', row.attr_info)
          })
          break
        default:
      }
    },
    getGroupNameById(id) {
      if (!id) {
        return null
      }
      for (let i = 0; i < this.attrGroupTableData.length; i++) {
        if (this.attrGroupTableData[i].id === id) {
          return this.attrGroupTableData[i].name
        }
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
.main-panel {
  padding: 18px;
  font-size: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.pImg {
  p > img {
    max-width: 100%
  }
}

</style>

~~~
